<template>
	<div id="friend-merchant-manage" class="w-h-100 pos-r flex-1 apply-container" style="box-sizing: border-box; overflow: hidden">
		<div class="w-h-100 ver-flex pos-a" style="box-sizing: border-box; padding: 6px">
			<div class="search-s page-public-s" style="box-sizing: border-box">
				<el-card shadow="never" :body-style="{ paddingBottom: '0' }">
					<el-form class="box-f" ref="queryForm" :inline="true">
						<!-- <el-form-item label="法律名称：">
                            <el-input v-model="transferVal" placeholder="请输入法律名称" />
                        </el-form-item> -->

						<el-form-item>
							<el-button v-if="$hasPer('LawsRegulations1:add')" @click="nodeClick" icon="ele-Plus" type="primary"> 新增</el-button>
							<el-button v-if="$hasPer('LawsRegulations7:excel')" @click="handleExport" icon="ele-Download"> 导出数据 </el-button>
							<el-button v-if="$hasPer('LawsRegulations2:download')" icon="ele-Download" @click="down"> 下载模板 </el-button>
							<el-upload v-if="$hasPer('LawsRegulations3:export')" action="#" :limit="1" :auto-upload="false" :show-file-list="false" accept=".xlsx" :on-change="(file:any) => {uploadFile1(file)}" style="margin-left: 10px; padding-top: 4px">
								<template #trigger>
									<el-button icon="ele-Upload">导入Excel</el-button>
								</template>
							</el-upload>
						</el-form-item>
					</el-form>
				</el-card>
			</div>

			<div style="box-sizing: border-box" class="flex-1 pos-r">
				<div class="pos-a w-h-100" style="box-sizing: border-box">
					<el-card class="box-card w-h-100" shadow="never" style="margin-top: 16px">
						<div style="" class="w-h-100 ver-flex">
							<div class="flex-1 pos-r">
								<div class="pos-a w-h-100">
									<el-table ref='excelRef' :data="list" class="w-h-100" style="width: 100%" border v-loading="loading" element-loading-background="rgba(0, 0, 0, 0.5)">
										<el-table-column type="index" label="序号" width="55" :show-overflow-tooltip="true" align="center" :index="indexMethod" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="法律名称" align="center">
											<el-table-column min-width="120" :show-overflow-tooltip="true" align="center">
												<template #header>
													<SearchModel typeId="v_LegalName" typeVal="input" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
												</template>
												<template #default="{ row }">
													{{ row.v_LegalName }}
												</template>
											</el-table-column>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="v_StandardCode" label="标准代号" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="d_PublicationDate" :formatter="formatDate" label="公布修正日期" align="center" />
										<el-table-column min-width="120" :formatter="formatDate" :show-overflow-tooltip="true" prop="d_EffectiveDate" label="生效日期" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true"  label="适用范围" prop="v_ScopeApplication" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="n_isValid" label="清单数量" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="createdUserName" label="创建人" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="createdTime" label=" 创建时间" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="更新人" align="center">
											<template #default="scope">
												<span v-if="scope.row.updatedUserName">{{ scope.row.updatedUserName }}</span>
												<span v-else> - </span>
											</template>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="更新时间" align="center">
											<template #default="scope">
												<span v-if="scope.row.updatedTime">{{ scope.row.updatedTime }}</span>
												<span v-else> - </span>
											</template>
										</el-table-column>
										<el-table-column min-width="180" label="操作" align="center" fixed="right">
											<el-table-column min-width="180" align="center" fixed="right">
												<template #header>
													<el-button @click="searchClick" icon="ele-Search" type="primary" text> 查询</el-button>
													<el-button @click="resetClick" icon="ele-Refresh" text> 重置 </el-button>
												</template>
												<template #default="scope">
													<div class="operate-s">
														<el-button v-if="$hasPer('LawsRegulations4:edit')" @click="nodeClick(scope.row)" class="icon-e" icon="ele-Edit" size="small" text type="primary"> 编辑 </el-button>
														<el-button v-if="$hasPer('LawsRegulations5:file')" size="small" @click="documentClick(scope.row)" text type="primary"> 附件管理 </el-button>
														<el-button v-if="$hasPer('LawsRegulations6:delete')" @click="deleteHandle(scope.row.n_Id, getData)" class="icon-e" icon="ele-Delete" size="small" text type="danger"> 删除 </el-button>
													</div>
												</template>
											</el-table-column>
										</el-table-column>
									</el-table>
								</div>
							</div>
							<div style="height: 30px; margin-top: 20px" class="hr-flex-start">
								<el-pagination
									v-model:currentPage="pageNo"
									v-model:page-size="pageSize"
									:total="totalRows"
									:page-sizes="[10, 20, 50, 100]"
									small
									background
									@size-change="handleSizeChange"
									@current-change="handleCurrentChange"
									layout="total, sizes, prev, pager, next, jumper"
									class="w-h-100"
								/>
							</div>
						</div>
					</el-card>
				</div>
			</div>
		</div>
		<!-- 新增and编辑 -->
		<el-dialog draggable :close-on-click-modal="false" :close-on-press-escape="false" v-model="showDialogVisible" :title="editId ? '编辑' : '新增'" width="50%" @close="cancelUseClick">
			<el-form :model="ruleForm" size="default" label-width="110px" ref="formRef" :rules="rules">
				<el-divider content-position="left"> 基本信息 </el-divider>
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="N_LegalTypeId" label="法例类型">
							<el-select v-model="ruleForm.N_LegalTypeId" class="m-2" placeholder="请选择法例类型" style="width: 100%">
								<el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="V_LegalName" label="法例名称">
							<el-input v-model="ruleForm.V_LegalName" placeholder="请输入法例名称" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="V_StandardCode" label="标准代号">
							<el-input v-model="ruleForm.V_StandardCode" placeholder="请输入标准代号" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="V_ScopeApplication" label="适用范围">
							<el-input v-model="ruleForm.V_ScopeApplication" placeholder="请输入适用范围" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="D_PublicationDate" label="公布修正日期">
							<el-date-picker style="width: 100%" v-model="ruleForm.D_PublicationDate" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" placeholder="请选择公布修正日期" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="D_EffectiveDate" label="生效日期">
							<el-date-picker style="width: 100%" v-model="ruleForm.D_EffectiveDate" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" placeholder="请选择生效日期" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="V_Remake" label="备注">
							<el-input type="textarea" v-model="ruleForm.V_Remake" placeholder="请输入备注" clearable />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancelUseClick">取消</el-button>
					<el-button type="primary" @click="controlUseClick(formRef, getData)">确定</el-button>
				</span>
			</template>
		</el-dialog>
		<!-- 文件 -->
		<uploadFile isAccept="" :fileInfo="fileInfo" :isUseDialog="fileDialog" @cancelFileClick="cancelFileClick" @controlFileClick="controlFileClick" @updateData="getData" />
	</div>
</template>
<script lang="ts">
import { defineComponent, ref, Ref, onMounted, reactive } from 'vue';
import getTableData from '/@/utils/getTableData';
import { ElMessageBox, ElMessage, FormInstance } from 'element-plus';
import useCurrentInstance from '/@/utils/hook/useCurrentInstance';
import uploadFile from '/@/views/sms/component/reviseUploadFile.vue';
import { fileToBase64, downUrl } from '/@/utils/hook/index';
// import { postExcel1 } from '/@/api/safety-play/discernAPI';
import { getRegulationList, postDeleteRegulation, postRegulation, postChangeRegulation, postExcel1 } from '/@/api/sms/HazardousChemicalsInterface';
import { sysDictDataList } from '/@/api/centerControl/pubilc';
import SearchModel from '/@/views/sms/component/search-model.vue';
import { exportToExcel } from '/@/utils/exportToExcel';
export default defineComponent({
	name: 'friend-merchant-manage',
	components: {
		SearchModel,
		uploadFile,
	},
	setup(props) {
		const { proxy } = useCurrentInstance();
		const $t = proxy.$t;

		const isUseDialog = ref(); // 新增/编辑弹出框隐藏/显示
		const repairInfo = ref(); // 传递子组件数据
		const searchVal = ref('1');

		const projectNam = ref(); // 友商名称数据
		const cliSta = ref(); // 当前用户点击的状态 新增/编辑
		let searchObj: any = reactive({});
		const aModel: Ref = ref(null);
		const transferVal = ref(); // 需要查询的值
		const ruleForm = reactive({
			N_LegalTypeId: '',
			V_LegalName: '',
			V_ScopeApplication: '',
			V_StandardCode: '',
			D_PublicationDate: null,
			D_EffectiveDate: null,
			V_Remake: '',
		});

		/***** searchClick 查询按钮 *****/
		const searchClick = () => {
			// searchObj.SearchValue = transferVal.value
			let newObj = Object.keys(searInfo.value);
			if (newObj.length !== 0) {
				newObj.map((i: any) => {
					searchObj[i] = searInfo.value[i];
				});
			}
		};
		const resetClick = () => {
			searInfo.value = {};
			let newObj = Object.keys(searchObj);
			if (newObj.length !== 0) {
				newObj.map((i: any) => {
					searchObj[i] = '';
					// console.log(i);
				});
			}
			initInfoFun();
		};

		const down = () => {
			downUrl('http://8.129.209.198:39056/api/Upload/SMS/Batch/LegalCode.xlsx');
		};

		const uploadFile1 = async (item: any) => {
			let arr: any = [];
			arr.push(item.raw);
			// console.log(arr,params);
			// await postExcel1(arr);
			console.log(item);
			setTimeout(() => {
				postExcel1({ file: arr });
				ElMessage.success('上传成功');
			}, 100);
			// fileToBase64(params.file)
			//     .then(async (base64) => {
			//         console.log(base64, params); // 输出文件的Base64编码
			// await postExcel1({ ModelType: 'LegalCode', FileContent: base64 });
			//     })
			//     .catch((error) => {
			//         console.error(error); // 输出错误信息
			//     });
		};

		/*** nodeClick 新增/编辑 校验 */
		const formRef = ref<FormInstance>();
		const rules = reactive({
			N_LegalTypeId: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
			V_LegalName: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
			V_ScopeApplication: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
			V_StandardCode: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
			D_PublicationDate: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
			D_EffectiveDate: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
		});

		/*** nodeClick 新增/编辑点击事件 */
		const showDialogVisible = ref(false);
		const editId = ref(0);
		const options1: any = ref([]);
		const nodeClick = async (obj: any) => {
			options1.value = [];
			// ruleForm.DictDataIdName
			const res = await sysDictDataList({ typeCode: 'legal_code' });
			res.data.forEach((element: any) => {
				options1.value.push({
					label: element.value,
					value: element.id,
				});
			});
			if (obj.n_Id) {
				editId.value = obj.n_Id;
				ruleForm.N_LegalTypeId = obj.n_LegalTypeId;
				ruleForm.V_LegalName = obj.v_LegalName;
				ruleForm.V_ScopeApplication = obj.v_ScopeApplication;
				ruleForm.V_StandardCode = obj.v_StandardCode;
				ruleForm.D_PublicationDate = obj.d_PublicationDate;
				ruleForm.D_EffectiveDate = obj.d_EffectiveDate;
				ruleForm.V_Remake = obj.v_Remake;
			}
			showDialogVisible.value = true;
		};

		/*** cancelUseClick 取消事件 */
		const cancelUseClick = () => {
			showDialogVisible.value = false;
			formRef.value?.clearValidate();
			editId.value = 0;
			ruleForm.N_LegalTypeId = '';
			ruleForm.V_LegalName = '';
			ruleForm.V_ScopeApplication = '';
			ruleForm.V_StandardCode = '';
			ruleForm.D_PublicationDate = null;
			ruleForm.D_EffectiveDate = null;
			ruleForm.V_Remake = '';
		};

		/*** controlUseClick 提交事件 */
		const controlUseClick = async (formEl: FormInstance | undefined, updateFun: Function) => {
			if (!formEl) return;
			await formEl.validate((valid, fields) => {
				if (valid) {
					console.log('submit!');
					// let start = new Date(String(ruleForm.ReleaseDate));
					// let end = new Date(String(ruleForm.ExpirationDate));
					// console.log(start, end);
					// if (start > end) return ElMessage.warning('结束时间不能小于开始时间');
					if (editId.value) {
						const obj = Object.assign({ ...ruleForm, n_Id: editId.value });
						postChangeRegulation(obj).then((res: any) => {
							console.log(res, 'res');
							cancelUseClick();
							updateFun();
						});
					} else {
						postRegulation(ruleForm).then((res: any) => {
							console.log(res, 'res');
							cancelUseClick();
							updateFun();
						});
					}
				} else {
					console.log('error submit!', fields);
				}
			});
		};

		/*** 附件管理 */
		const fileInfo = ref();
		const fileDialog = ref(false);
		/*** cancelFileClick 文件上传取消事件 */
		const cancelFileClick = () => {
			fileDialog.value = false;
		};

		/*** controlFileClick 文件上传提交事件 */
		const controlFileClick = () => {
			fileDialog.value = false;
		};

		/*** documentClick 文档上传事件 */
		const documentClick = (val: any) => {
			console.log(val, 'val');
			val.sourceType = 10;
			val.sourceId = val.n_Id;
			val.titleCon = '上传制度文档';
			fileInfo.value = JSON.stringify(val);
			fileDialog.value = true;
		};

		/*** deleteHandle 删除数据事件 */
		const deleteHandle = async (val: String | Number, updateFun: Function) => {
			ElMessageBox.confirm('请确定删除此条数据', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(async () => {
					let param = { n_Id: val };
					try {
						let res: any = await postDeleteRegulation(param);
						if (res.success) {
							updateFun();
						}
					} catch (err) {
						return;
					}
				})
				.catch(() => {
					ElMessage({
						type: 'info',
						message: '删除失败',
					});
				});
		};

		/*** 初始化数据 */
		const basicsInfo: any = ref([]);
		const initInfoFun = () => {
			basicsInfo.value = [
				{
					typeId: 'v_LegalName', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
					typeNam: '', // 输入类型(number,text等) --- 选填
					searchVal: 'SearchValue', // 查询字段 --- 必填
					defaultVal: '', // 字段默认值 --- 选填
					placeholder: '法例名称', // placeholder数据
					defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
					eventType: '', // 事件类型（如burl/change等） --- 选填
					defaultEvent: '', // 事件名称 --- 选填
				},
				{
					typeId: 'v_ScopeApplication', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
					typeNam: '', // 输入类型(number,text等) --- 选填
					searchVal: 'V_ScopeApplication', // 查询字段 --- 必填
					defaultVal: '', // 字段默认值 --- 选填
					placeholder: '适用范围', // placeholder数据
					defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
					eventType: '', // 事件类型（如burl/change等） --- 选填
					defaultEvent: '', // 事件名称 --- 选填
				},
			];
		};

		const searInfo: any = ref();
		const searchHandel = (val: any) => {
			searInfo.value = val;
		};

		onMounted(() => {
			initInfoFun();
		});

		/*** 截取日期格式方法 */
		const formatDate = (row: any, column: any) => {
			// 获取单元格数据
			let data = row[column.property];
			if (data == null) {
				return '-';
			}
			if (data === '1900-01-01 00:00:00') {
				return '-';
			}
			let dt = new Date(data);
			let month = dt.getMonth() + 1 < 10 ? '0' + (dt.getMonth() + 1) : dt.getMonth() + 1;
			let date = dt.getDate() < 10 ? '0' + dt.getDate() : dt.getDate();
			return dt.getFullYear() + '-' + month + '-' + date;
		};

		  /*** ================================= 导出数据函数操作 ================================= */
		  const excelRef: any = ref(null);
        const handleExport = () => {
            if(excelRef.value){
                if(excelRef.value.data.length !== 0){
                    let tableExcel: any = [];
                    let tableArr = excelRef.value.data;
                    tableArr.map((item: any) => {
                        let tableObj: any = {};
                        tableObj['法律名称'] = item.v_LegalName ? item.v_LegalName : '-';
                        tableObj['标准代号'] = item.v_StandardCode ? item.v_StandardCode : '-';
						tableObj['公布修正日期'] = item.d_PublicationDate ? item.d_PublicationDate : '-';
                        tableObj['生效日期'] = item.d_EffectiveDate ? item.d_EffectiveDate : '-';
                        tableObj['适用范围'] = item.v_ScopeApplication ? item.v_ScopeApplication : '-';
                        tableObj['清单数量'] = item.n_isValid ? item.n_isValid : '-';

                        tableObj['创建人'] = item.createdUserName ? item.createdUserName : '-';
                        tableObj['创建时间'] = item.createdTime ? item.createdTime : '-';
                        tableObj['更新人'] = item.updatedUserName ? item.updatedUserName : '-';
                        tableObj['更新时间'] = item.updatedTime ? item.updatedTime : '-';
                        tableExcel.push(tableObj);
                    });
                    exportToExcel(tableExcel,'法律法规.xlsx');
                }else{
                    ElMessage({
                        type: 'error',
                        message: '暂无数据导出',
                    })
                }
            }
        }

		return {
			...getTableData(getRegulationList, {}, searchObj),
			isUseDialog,
			cancelUseClick,
			controlUseClick,
			nodeClick,
			resetClick,
			repairInfo,
			cliSta,
			deleteHandle,
			searchClick,
			aModel,
			searchVal,
			transferVal,
			projectNam, // 友商名称数据
			/***/
			showDialogVisible,
			ruleForm,
			editId,
			rules,
			fileDialog,
			fileInfo,
			controlFileClick,
			cancelFileClick,
			documentClick,
			options1,
			formRef,
			down,
			uploadFile1,
			basicsInfo,
			searchHandel,
			formatDate,
			handleExport,excelRef
		};
	},
});
</script>
<style lang="scss">
@import '../style/public.scss';
</style>
<style scoped lang="scss">
#friend-merchant-manage {
	.box-f {
		:deep(.el-form-item__label) {
			padding: 0;
		}
	}

	:deep(.el-card__body) {
		height: 100%;
	}

	:deep(.el-card) {
		border: none !important;
	}

	.upload-demo {
		margin-left: 12px;
		margin-top: 2px;
	}

	ul {
		list-style: none;

		li {
			cursor: pointer;

			&:hover {
				color: red;
			}
		}
	}

	.icon-e {
		:deep(.el-icon) {
			margin-right: 0px !important;
		}
	}
}
</style>
